from datetime import datetime
import logging
from flask import Blueprint, jsonify
from flask import current_app
from flask import g
from flask import request
from flask import session

from api_v1.my_decorators import is_login
from models import House, Order
from response_code import RET

order_blueprint = Blueprint('order', __name__, url_prefix="/api/v1/order")

# 指定房屋预定接口
@order_blueprint.route("/house/<int:id>")
@is_login
def order_house(id):
    try:
        house = House.query.get(id)
    except Exception as e:
        return jsonify(code=RET.DBERR, msg="数据库查询失败")
    return jsonify(code=RET.OK, house=house.to_dict())


# 房东订单查询
@order_blueprint.route('/fd', methods=['GET'])
@is_login
def master_lorders():
    """作为房东查询订单"""
    uid=session.get('user_id')
    #查询当前用户的所有房屋编号
    hlist=House.query.filter(House.user_id==uid).all()
    hid_list=[house.id for house in hlist]
    #根据房屋编号查找订单
    order_list=Order.query.filter(Order.house_id.in_(hid_list)).order_by(Order.id.desc())
    #构造结果
    olist=[order.to_dict() for order in order_list]
    return jsonify(olist=olist)


# 租客查询订单   预定订单
@order_blueprint.route('/', methods=['post', 'get'])
@is_login
def book_house():
    """租客查询订单"""
    if request.method == "GET":
        if g.user:
            uid = g.user.id
        order_list = Order.query.filter(Order.user_id == uid).order_by(Order.id.desc()).all()
        order_list2 = [order.to_dict() for order in order_list]
        return jsonify(olist=order_list2)

    # 预定房屋接口
    # 1.判断用户是否登陆
    if not g.user:
        return jsonify(code=RET.SESSIONERR, msg="用户未登陆")
    # 2.获取参数
    house_id = request.form.get("house_id")
    start_date = request.form.get("start_date")
    end_date = request.form.get("end_date")
    start_date = datetime.strptime(start_date, '%Y-%m-%d')
    end_date = datetime.strptime(end_date, '%Y-%m-%d')
    # 3.1校验参数
    if not all([house_id, start_date, end_date]):
        return jsonify(code=RET.PARAMERR, msg="参数不全")
    # 3.2校验日期参数
    if start_date > end_date:
        return jsonify(code=RET.PARAMERR, msg="日期格式错误")
    days = (end_date - start_date).days + 1
    try:
        house = House.query.get(house_id)
    except Exception as e:
        current_app.logger.error(e)
        return jsonify(code=RET.DBERR, msg="数据库错误")

    if not house:
        return jsonify(code=RET.DBERR, msg="房屋不存在")

    # 4.数据入库
    order = Order()
    order.house_id = house_id
    order.house_price = house.price
    order.amount = house.price * days
    order.begin_date = start_date
    order.end_date = end_date
    order.user_id = g.user.id
    order.days = int(days)
    try:
        order.add_update()
    except Exception as e:
        logging.error(e)
        return jsonify(code=RET.DBERR, msg="数据库错误")
    return jsonify(code=RET.OK, msg="success")

#修改订单状态
@order_blueprint.route('/<int:oid>', methods=['put'])
@is_login
def xiuGai(oid):
    status = request.form.get("status")
    # 判断类型
    if not status in ['WAIT_PAYMENT', 'REJECTED']:
        return jsonify(code=RET.DATAERR)

    # 查询订单对象
    try:
        order = Order.query.filter(Order.id == oid).first()
    except Exception as e:
        logging.error(e)
        return jsonify(code=RET.DATAERR)

    # 判空
    if not order:
        return jsonify(code=RET.DATAERR)

    # 判断类型，修改状态
    if status == "WAIT_PAYMENT":
        order.status = "WAIT_PAYMENT"
    else:
        order.status = "REJECTED"

    # 提交数据库
    order.add_update()

    return jsonify(code=RET.OK)
